export interface FeedingPayload {
  babyId: number;
  eventTime: string;
  feedingType: 'BREAST_MILK' | 'FORMULA';
  leftMinutes?: number;
  rightMinutes?: number;
  formulaMl?: number;
  note?: string;
}

export interface DiaperPayload {
  babyId: number;
  eventTime: string;
  diaperType: 'WET' | 'DIRTY' | 'MIXED';
  note?: string;
}

export interface SleepPayload {
  babyId: number;
  sleepStart: string;
  sleepEnd?: string;
  note?: string;
}

export interface CryPayload {
  babyId: number;
  startTime: string;
  endTime?: string;
  reasons: (
    | 'HUNGRY'
    | 'SLEEPY'
    | 'DIAPER'
    | 'COMFORT'
    | 'STOMACH'
    | 'TOO_HOT'
    | 'TOO_COLD'
    | 'OTHER'
  )[];
  sootheWays: ('FEED' | 'HUG' | 'CHANGE_DIAPER' | 'PACIFIER' | 'PLAY' | 'OTHER')[];
  note?: string;
}

export interface RecordsByDatePayload { babyId: number; date: string }
export interface TimelineByDatePayload { babyId: number; date: string }
export interface StatsOverviewPayload { babyId: number; startDate: string; endDate: string }

// 获取认证头
function getAuthHeaders(): HeadersInit {
  const token = localStorage.getItem('auth_token');
  console.log('API请求 - token:', token);
  return {
    'Content-Type': 'application/json',
    ...(token && { 'Authorization': `Bearer ${token}` })
  };
}

// 后端服务器地址 - 从环境变量获取，开发环境默认值
const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080';

// 导出 API 基础配置，供其他组件使用
export const API_CONFIG = {
  BASE_URL: API_BASE,
  MEDIA_BASE: import.meta.env.VITE_PUBLIC_MEDIA_BASE || '/media'
};

async function http<T>(url: string, init?: RequestInit): Promise<T> {
  const fullUrl = url.startsWith('http') ? url : `${API_BASE}${url}`;
  console.log('API请求 - URL:', fullUrl);
  console.log('API请求 - Headers:', getAuthHeaders());
  
  const resp = await fetch(fullUrl, {
    ...init,
    headers: {
      ...getAuthHeaders(),
      ...init?.headers
    }
  });
  if (!resp.ok) {
    const text = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${text}`);
  }
  return (await resp.json()) as T;
}

export async function health() {
  return http<{ status: string; service: string }>(`/api/health`);
}

// ================= Auth =================
export interface LoginPayload {
  account: string;  // 手机号或邮箱
  password: string;
}

export interface RegisterPayload {
  account: string;
  password: string;
  nickname?: string;
}

export interface AuthResponse {
  token: string;
  user: {
    id: number;
    familyId: number;
    role: 'PARENT' | 'GUARDIAN';
    nickname?: string;
  };
}

export async function login(payload: LoginPayload) {
  return http<AuthResponse>(`/api/auth/login`, {
    method: 'POST',
    body: JSON.stringify(payload)
  });
}

export async function register(payload: RegisterPayload) {
  return http<AuthResponse>(`/api/auth/register`, {
    method: 'POST',
    body: JSON.stringify(payload)
  });
}

export async function logout() {
  localStorage.removeItem('auth_token');
}

export async function createFeeding(payload: FeedingPayload) {
  return http(`/api/records/feeding`, {
    method: 'POST',
    body: JSON.stringify(payload)
  });
}

export async function createDiaper(payload: DiaperPayload) {
  return http(`/api/records/diaper`, {
    method: 'POST',
    body: JSON.stringify(payload)
  });
}

export async function createSleep(payload: SleepPayload) {
  return http(`/api/records/sleep`, {
    method: 'POST',
    body: JSON.stringify(payload)
  });
}

export async function createCry(payload: CryPayload) {
  return http(`/api/records/cry`, {
    method: 'POST',
    body: JSON.stringify(payload)
  });
}

export async function recordsByDate(payload: RecordsByDatePayload) {
  return http(`/api/records/by-date`, {
    method: 'POST',
    body: JSON.stringify(payload)
  });
}

export async function timelineByDate(payload: TimelineByDatePayload) {
  return http(`/api/timeline/by-date`, {
    method: 'POST',
    body: JSON.stringify(payload)
  });
}

export async function statsOverview(payload: StatsOverviewPayload) {
  return http(`/api/stats/overview`, {
    method: 'POST',
    body: JSON.stringify(payload)
  });
}

// ================= Media =================
export interface MediaAsset {
  id: number;
  objectKey: string;
  contentType: string;
  description?: string;
  createdAt: string;
}

export async function listMedia(babyId: number) {
  return http<MediaAsset[]>(`/api/media/list?babyId=${encodeURIComponent(babyId)}`);
}

export async function uploadMedia(payload: { babyId: number; file: File; description?: string }) {
  const form = new FormData();
  form.append('babyId', String(payload.babyId));
  form.append('file', payload.file);
  if (payload.description) form.append('description', payload.description);
  
  const token = localStorage.getItem('auth_token');
  const resp = await fetch(`/api/media/upload`, { 
    method: 'POST', 
    body: form,
    headers: {
      ...(token && { 'Authorization': `Bearer ${token}` })
    }
  });
  if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
  return (await resp.json()) as MediaAsset;
}

export async function deleteMedia(id: number) {
  const token = localStorage.getItem('auth_token');
  const resp = await fetch(`/api/media/${id}`, { 
    method: 'DELETE',
    headers: {
      ...(token && { 'Authorization': `Bearer ${token}` })
    }
  });
  if (!resp.ok && resp.status !== 204) throw new Error(`HTTP ${resp.status}`);
}

export function buildMediaUrl(objectKey: string): string {
  const base = import.meta.env.VITE_PUBLIC_MEDIA_BASE as string | undefined;
  // 当未配置时，回退到相对路径（需要后端静态代理支持）
  return base ? `${base.replace(/\/$/, '')}/${objectKey}` : `/media/${objectKey}`;
}

// ================= Family & Settings =================
export interface FamilySetting {
  notifyFeeding: boolean;
  notifySleep: boolean;
  notifyDiaper: boolean;
}

export interface BabyProfile {
  id?: number;
  nickname?: string;
  birthday?: string; // YYYY-MM-DD
  gender?: 'M' | 'F';
  avatarUrl?: string;
}

export async function getFamily(id: number) {
  return http<any>(`/api/family/${id}`);
}

export async function getFamilyBabies(familyId: number) {
  return http<any[]>(`/api/family/${familyId}/babies`);
}

export async function updateFamilySettings(id: number, setting: FamilySetting) {
  return http<FamilySetting>(`/api/family/${id}/settings`, {
    method: 'POST',
    body: JSON.stringify(setting)
  });
}

export async function upsertBaby(familyId: number, baby: BabyProfile) {
  return http<BabyProfile>(`/api/family/${familyId}/baby`, {
    method: 'POST',
    body: JSON.stringify(baby)
  });
}


